# 处理websocket路由发送的请求和数据

import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
import datetime

from django.db.models import Count

from . import models


# 用户receiver收到sender发送的所有消息，标记为已读
def update_notify(sender, receiver):
    models.ChatMessage.objects.filter(sender=sender, receiver=receiver, read=False).update(read=True)

# 聊天
class ChatConsumer(WebsocketConsumer):
    # websocket建立连接时执行方法
    def connect(self):
        # 从url里获取聊天室名字，为每个房间建立一个频道组
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.user_id = self.scope['url_route']['kwargs']['user_id']
        self.room_group_name = 'chat_%s' % self.room_name

        # 将当前频道加入频道组
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )
        # 查看是否在表里`
        group_obj = models.ChatGroup.objects.filter(group = self.room_name).first()
        # print(self.room_name,group_obj)
        if group_obj is not None:
            print(group_obj.id1,group_obj.id2,self.user_id)
            if str(group_obj.id1) == str(self.user_id):
                # 满足条件
                self.receiver = str(group_obj.id2) # 存储另一个用户的id
                self.accept()
                self.initial_data()
            elif str(group_obj.id2) == str(self.user_id):
                self.receiver = str(group_obj.id1)  # 存储另一个用户的id
                self.accept()
                self.initial_data()
            else:
                self.close()
        else:
            self.close()

    def initial_data(self):
        # 从数据库获取之前的聊天记录并显示
        msg_objs = models.ChatMessage.objects.filter(group=self.room_name)  # 找出这两个人的聊天
        for obj in msg_objs:
            self.send(text_data=json.dumps({
                'id': obj.id,  # 用于标识消息，客户端收到某条消息后，返回收到的消息的id号，服务器将其置为已读
                'sender': obj.sender,
                'receiver': obj.receiver,
                'message': obj.content,
                'time': str(obj.timestamp),
                'senderavatar': models.UserInfo.objects.get(id=obj.sender).avatar,
                'receiveravatar': models.UserInfo.objects.get(id=obj.receiver).avatar,
            }))


    # websocket断开时执行方法
    def disconnect(self, close_code):
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    # 从websocket接收到消息时执行函数
    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        # 发送消息到频道组，频道组调用chat_message方法
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message
            }
        )

    # 从频道组接收到消息后执行方法
    def chat_message(self, event):
        message = event['message']
        datetime_str = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        # 存储到数据库中
        count = models.ChatMessage.objects.count()
        msg_obj = models.ChatMessage(
            id = count + 1 ,
            sender = self.user_id,
            receiver = self.receiver,
            content = message,
            timestamp = datetime_str,
            group = self.room_name,
            read = False # 客户端向服务器发送消息，此时该消息还未被receiver接收，为未读
        )
        msg_obj.save()

        # 通过websocket发送消息到客户端
        self.send(text_data=json.dumps({
            'id': count + 1,  # 当前该消息的序号
            'sender': self.user_id,
            'receiver': self.receiver,
            'message': message,
            'time': datetime_str,
            'senderavatar': models.UserInfo.objects.get(id=self.user_id).avatar,
            'receiveravatar': models.UserInfo.objects.get(id=self.receiver).avatar,
        }))


def system_notify(user_id,msg):
    # 传入需要发送给哪个用户，发送的具体信息
    # 检查数据库中是否有系统向用户发送的值
    exists = models.ChatGroup.objects.filter(group = -user_id)
    if not exists:
        # 不存在系统向用户发送聊天请求的群组
        count_ = models.ChatGroup.objects.count()
        models.ChatGroup.objects.create(
            id = count_,
            id1 = 0, # 系统向用户发送消息
            id2 = user_id,
            group = -user_id
        )

    # 存储到数据库中
    datetime_str = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    count = models.ChatMessage.objects.count()
    msg_obj = models.ChatMessage(
        id=count + 1,
        sender=0, # 系统通知，系统的id设置为0
        receiver=user_id,
        content=msg,
        timestamp=datetime_str,
        group=-user_id, # 房间号为-id
        read=False  # 客户端向服务器发送消息，此时该消息还未被receiver接收，为未读
    )
    msg_obj.save()




